package com.hu.article.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hu.article.feign.UserClient;
import com.hu.article.service.IBlogService;
import com.hu.common.common.HttpStatus;
import com.hu.common.controller.BaseController;
import com.hu.common.pojo.Blog;
import com.hu.common.pojo.User;
import com.hu.common.pojo.dto.Response;
import com.hu.common.utils.CompletionDateUtils;
import com.hu.common.vo.BlogChartsVo;
import com.hu.common.vo.BlogPraiseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hu
 * @since 2023-09-07
 */
@RestController
@RequestMapping("/blog")
public class BlogController extends BaseController {

    @Autowired
    private IBlogService blogService;

    @Autowired
    private UserClient userClient;


    private final String now = DateUtil.now();

    // 发布博客
    @PostMapping
    public Response save(@RequestBody Blog blog, ServerWebExchange exchange) {
        blog.setTime(DateUtil.now());
        blogService.save(blog);
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> list = headers.get("token");
        String token = list.get(0);
        User user = userClient.getUserByToken(token);
        System.out.println("blog------------>"+user);
        String successInfo = user.getNickname() + "发布了博客: " + blog.getTitle();
        System.out.println("success--------->"+successInfo);
//        try {
//            WebSocketServer.sendInfo(successInfo ,"2");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return success();
    }

    /**
     * 修改博客
     * @param
     * @return
     */
    @PostMapping("/update")
    public Response update(@RequestBody Blog blog) {
        blogService.saveOrUpdate(blog);
        return success();
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        blogService.removeById(id);
        return success();
    }

    @PostMapping("/del/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        blogService.removeByIds(ids);
        return success();
    }

    @GetMapping
    public Response findAll() {
        return success(blogService.list());
    }

    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        try {
            // 调用接口，添加阅读量
            blogService.addReadCount(id);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        }
        return success(blogService.getById(id));
    }

    @GetMapping("/page")
    public Response findPage(@RequestParam(defaultValue = "") String title,
                           @RequestParam String authorId,
                           @RequestParam String order,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        // 根据不同的排序字段进行动态排序
        if (!"".equals(order)) {
            // equalsIgnoreCase 方法是 Java 中字符串比较的一个方法，它用于比较两个字符串的内容是否相等，但不区分字符的大小写。
            if ("readCount".equalsIgnoreCase(order)) {
                queryWrapper.orderByDesc("read_count");
            } else if ("commentCount".equalsIgnoreCase(order)) {
                queryWrapper.orderByDesc("comment_count");
            } else if ("praise".equalsIgnoreCase(order)) {
                queryWrapper.orderByDesc("praise");
            }else {
                // 默认排序方式，可以根据需要修改
                queryWrapper.orderByDesc("id");
            }
        } else {
            // 默认排序方式，可以根据需要修改
            queryWrapper.orderByDesc("id");
        }
        if (!"".equals(title)) {
            queryWrapper.like("title", title);
        }
        if (!"".equals(authorId)) {
            queryWrapper.eq("author_id",authorId);
        }
        return success(blogService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Blog> list = blogService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Blog信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
        }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Response imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Blog> list = reader.readAll(Blog.class);
        blogService.saveBatch(list);
        return success();
    }


    @PostMapping("/praise")
    public Response praise(@RequestBody BlogPraiseVo blogPraiseVo) {
        Boolean praise = blogService.isPraise(blogPraiseVo.getBlogId(), blogPraiseVo.getUserId());
        if (praise) {
            return error(HttpStatus.BAD_REQUEST,"你已经点过赞了~~");
        }else {
            blogService.setPraise(blogPraiseVo.getBlogId(),blogPraiseVo.getUserId());
            return success(HttpStatus.SUCCESS, "点赞成功");
        }
    }

    @GetMapping("/charts")
    public Response findBlogCharts(@RequestParam String startTime,
                                    @RequestParam String endTime) {
        List<BlogChartsVo> blogCharts = blogService.findBlogCharts(startTime, endTime);

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime startDateTime = LocalDate.parse(startTime, df).atStartOfDay();
        LocalDateTime endDateTime = LocalDate.parse(endTime, df).atStartOfDay();
        //3.补全为空的日期
        //补全后的结果
        List<BlogChartsVo> result = new ArrayList<>();
        boolean dbDateExist = false;
        List<String> dateList = CompletionDateUtils.completionDate(startDateTime, endDateTime);
        for (String date : dateList) {
            //table为数据库查询出来的对象列表，结构为List<Map<String, Object>>
            for (BlogChartsVo blogChartsVo : blogCharts) {
                if (blogChartsVo.getPublishDate().equals(date)) {
                    //集合已包含该日期
                    dbDateExist = true;
                    result.add(blogChartsVo);
                    break;
                }
            }
            //添加补全的数据到最后结果列表
            if (!dbDateExist) {
                BlogChartsVo blogChartsVo = new BlogChartsVo();
                blogChartsVo.setPublishDate(date);
                blogChartsVo.setNum(0);
                result.add(blogChartsVo);
            }
            //状态修改为不存在
            dbDateExist = false;
        }
        return success(result);
    }
}

